import { TableActionType } from '/@/components/Table';
import { isNullOrUnDef } from '/@/utils/is';
import { DelBatchType } from './types/index';

import { commonBatchApi, ModelIds } from '/@/api/config-center/model-design';
import {
  deleteFlowProcessApi,
  deleteTransferFlowApi,
  getRecallWorkItemApi,
} from '/@/api/flow/flow';
import { useMessage } from '/@/hooks/web/useMessage';
import { formhandSchema, formbatchSchema, formconsultSchema } from './components/flow-data';
import { BTN_EVENT_TYPE } from '/@/views/config-center/model-design/model';

const { createMessage, createConfirm, createWarningModal } = useMessage();

export function checkFlowFn(arr) {
  const isPassArr = arr.filter((item) => Number(item.ConfigTransfer.value) != 0);
  const isFailArr = arr.filter((item) => Number(item.ConfigTransfer.value) == 0);

  return { isPassArr, isFailArr };
}

export function getRowKeys(key: string, record: Recordable) {
  if (isNullOrUnDef(key)) return {};
  const keys = key.split(',');
  const params = {};
  for (const key of keys) {
    if (key) {
      params[key] = record[key];
    }
  }
  return params;
}

/**
 *
 * @param res 数组
 * @param plural 是否选择多个
 * @returns Promise(Array)
 */
export function getSelectRowsFn<T = any>(res, plural = false): Promise<T> {
  return new Promise((resolve, reject) => {
    if (!res.length) {
      createMessage.warning('请选择需要操作的数据！');
      reject('请选择需要操作的数据！');
    }

    if (res.length > 1 && !plural) {
      createMessage.warning('不可操作多个');
      reject('不可操作多个');
    }

    resolve(res);
  });
}

// 通用模型删除，流程草稿、流程传阅多个删除，
export async function handleBatchDel(
  type: DelBatchType,
  { moduleId, primaryKey, tableModelId }: Recordable,
  tableFn: TableActionType,
) {
  const ids: ModelIds = { moduleId, modelId: tableModelId };

  const res = tableFn.getSelectRows();
  if (!res.length) {
    createMessage.warning('未选择数据');
    return;
  }
  createConfirm({
    iconType: 'warning',
    title: '提示',
    content: '是否批量删除选择的数据',
    onOk: async () => {
      const data = res.map((record) => {
        return getRowKeys(primaryKey, record);
      });
      try {
        switch (type) {
          case DelBatchType.FLOWDELETE:
            const workItemIdList = res.map((item) => Number(item.WorkItemID));
            await deleteFlowProcessApi({ workItemIdList });
            break;
          case DelBatchType.FLOWHANDROUNDDELETE:
            console.log('res2', res);
            const transferWorkItemIdList = res.map((item) => item.ID);
            await deleteTransferFlowApi({ transferWorkItemIdList });
            break;
          default:
            await commonBatchApi(ids, { idList: data });
            break;
        }
        tableFn.reload && tableFn.reload();
        createMessage.success('操作成功');
      } catch (e) {
        throw e;
      }
    },
  });
}

export async function getRecallWorkItemFn(seclectRows, callback) {
  const res = await getSelectRowsFn(seclectRows);
  console.log('res', res);

  const { WorkItemID, EntryID, WorkItemName } = res[0];
  createConfirm({
    iconType: 'warning',
    title: '提示',
    content: `是否撤回${WorkItemName}!`,
    onOk: async () => {
      const recallRes = await getRecallWorkItemApi({ workItemID: WorkItemID, entryID: EntryID });
      if (!recallRes) {
        createMessage.success('撤回成功');
        callback();
      } else {
        createWarningModal({
          title: '提示',
          content: recallRes,
        });
      }
    },
  });
}

export function getBtnFormScheama(btnItem) {
  if (!btnItem) {
    return formhandSchema;
  }

  const { eventType, isUpdate } = btnItem;
  if (BTN_EVENT_TYPE.FLOWTURNBATCH === eventType) {
    return formbatchSchema;
  } else if (BTN_EVENT_TYPE.FLOWCONSULT === eventType && isUpdate) {
    console.log('dd');
    return formconsultSchema;
  } else {
    return formhandSchema;
  }
}
